//创建menu
var userBusinessList = null;
var type = null;
var options = "";
var kid = null;
var lei = null;
var functions = "";
var btnStrList = []; //按钮权限列表

//初始化系统基础信息
function initSystemData(kid, type) {
    console.log("initSystemData - kid:", kid, "type:", type);
    $.ajax({
        type: "get",
        url: "/userBusiness/getBasicData",
        data: ({
            KeyId: kid,
            Type: type
        }),
        //设置为同步
        async: false,
        dataType: "json",
        success: function (res) {
            console.log("initSystemData response:", res);
            if (res && res.code === 200) {
                userBusinessList = res.data.userBusinessList;
                console.log("userBusinessList:", userBusinessList);
            } else {
                userBusinessList = null;
            }
        }
    });
}

//初始化页面选项卡
function initSelectInfo(lei) {
    console.log("initSelectInfo - lei:", lei, "userBusinessList:", userBusinessList);
    if (userBusinessList != null) {
        if (userBusinessList.length > 0) {
            options = userBusinessList[0].value;
            console.log("options:", options);
            if (options != "") {
                options = options.substring(1, options.length - 1);
            }
            //功能菜单列表
            if (lei == 2) {
                functions += options + '][';
                console.log("functions after adding:", functions);
            }
            //按钮权限列表
            else if (lei == 3) {
                var btnStr = userBusinessList[0].btnstr;
                if (btnStr != null) {
                    var btnObj = JSON.parse(btnStr);
                    for (var j = 0; j < btnObj.length; j++) {
                        btnStrList.push(btnObj[j]);
                    }
                }
            }
        }
    }
}

var id = sessionStorage.getItem("userId");
console.log("Current user ID:", id);
initSystemData(id, 'UserRole');
initSelectInfo(1);
var arr = options.split('][');
console.log("Role array:", arr);
for (var i in arr) {
    console.log("Processing role:", arr[i]);
    initSystemData(arr[i], 'RoleFunctions'); //根据角色找functions
    initSelectInfo(2); //功能菜单列表
    initSelectInfo(3); //查询角色对应的按钮权限
}
if (functions != "") {
    functions = "[" + functions.substring(0, functions.length - 1);
    console.log("Final functions string:", functions);
}
if (btnStrList.length > 0) {
    window.winBtnStrList = JSON.stringify(btnStrList); //将按钮功能列表存为全局变量
}

console.log("About to call /functions/findMenu with functions:", functions);
$.ajax({
    type: "post",
    url: "/functions/findMenu",
    data: ({
        pNumber: 0,
        hasFunctions: functions
    }),
    dataType: "json",
    async: false,
    success: function (res) {
        console.log("findMenu response:", res);
        if (res) {
            // 过滤掉名称包含"零售""财务""仓库""管理"的一级和二级菜单，并过滤掉id为245的插件管理菜单
            function filterMenu(menuArr) {
                if (!Array.isArray(menuArr)) return menuArr;
                return menuArr.filter(function(item) {
                    // 递归过滤子菜单
                    if (item.children && item.children.length > 0) {
                        item.children = filterMenu(item.children);
                    }
                    // 过滤掉插件管理菜单（id为245，兼容字符串和数字）
                    if (item.id == 245 || item.id == "245") {
                        return false;
                    }
                    return true;
                });
            }
            var json = {};
            json.menu = filterMenu(res);
            console.log("Filtered menu:", json.menu);
            console.log("Menu data structure:", JSON.stringify(json.menu, null, 2));
            $.ajax({
                type: "get",
                url: "../../../pages/template/menu.html?1515",
                async: false,
                success: function (tem) {
                    console.log("Menu template:", tem);
                    if (tem) {
                        var template = Handlebars.compile(tem);
                        var htmlValue = template(json);
                        console.log("Generated HTML:", htmlValue);
                        console.log("JSON data passed to template:", JSON.stringify(json, null, 2));
                        $(".sidebar-menu").html(htmlValue);
                    }
                }
            });
        }
    }
});